import { login, fetchSSQ } from '@/api/user'
import { getToken, setToken, removeToken, setUserInfo, getUserInfo } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  addressOptions: [],
  loginName: '',
  info: {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_LOGINNAME: (state, name) => {
    state.loginName = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
  SET_ADDRESS: (state, address) => {
    state.addressOptions = address
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: username.trim(), password: password }).then(response => {
        const { data } = response
        const { Area, City, JWT, Level, LoginName, Name, PhoneNumber, Province } = data
        commit('SET_TOKEN', JWT)
        setToken(JWT)
        setUserInfo(JSON.stringify({
          Area,
          City,
          Level,
          LoginName,
          Name,
          PhoneNumber,
          Province,
          avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        }))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    let info = getUserInfo()
    info = JSON.parse(info)
    commit('SET_ROLES', ['admin'])
    commit('SET_NAME', info.Name)
    commit('SET_LOGINNAME', info.LoginName)
    commit('SET_AVATAR', info.avatar)
    commit('SET_INTRODUCTION', '')
    commit('SET_INFO', info)

    fetchSSQ().then((res) => {
      const address = res.data || []
      const _address = transAddress(address)
      commit('SET_ADDRESS', _address)
    })

    function transAddress(arr) {
      return arr.map((item) => {
        if (item.children) {
          item = {
            ...item,
            label: item.name,
            value: item.name,
            children: transAddress(item.children)
          }
        } else {
          item = {
            ...item,
            label: item.name,
            value: item.name,
          }
        }
        return item
      })
    }
  },

  // user logout
  logout({ commit, state, dispatch }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    removeToken()
    resetRouter()
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
